package sipus.common;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import sipus.database.hibernate.HibernateUtil;
import sipus.database.model.AccessedUsers;
import sipus.database.model.LogLogin;
import sipus.database.model.OnlineUsers;


public class LogoutListener implements LogoutSuccessHandler {

	@Override
	public void onLogoutSuccess(HttpServletRequest arg0,
			HttpServletResponse arg1, Authentication arg2) throws IOException,
			ServletException {

		Session mySession = HibernateUtil.getSessionFactory().openSession();

		HttpSession session = arg0.getSession();
		System.out
				.println("=============================================================== USER LOGOUT SUCCESS, SESSION ID = "
						+ session.getId()
						+ " ====================================================================== ");

		OnlineUsers onlineUsers = (OnlineUsers) mySession
				.createCriteria(OnlineUsers.class)
				.createAlias("accessedUsers", "accessedUsers")
				.add(Restrictions.eq("accessedUsers.nama", session.getId()))
				.setMaxResults(1).uniqueResult();
		if (onlineUsers != null) {
			LogLogin login = onlineUsers.getLogin();
			if (login != null) {
				login.setLogout(new Date());
				mySession.getTransaction().begin();
				mySession.update(mySession.merge(login));
				mySession.getTransaction().commit();
			}
			System.out.println("Remove User Online " + onlineUsers.getNama());
			mySession.getTransaction().begin();
			mySession.delete(onlineUsers);
			mySession.getTransaction().commit();
		}

		AccessedUsers accessedUsers = (AccessedUsers) mySession
				.createCriteria(AccessedUsers.class)
				.add(Restrictions.eq("nama", session.getId())).setMaxResults(1)
				.uniqueResult();

		if (accessedUsers != null) {
			mySession.getTransaction().begin();
			mySession.delete(accessedUsers);
			mySession.getTransaction().commit();
		}

		mySession.disconnect();
		mySession.close();

		session.invalidate();
		arg0.getRequestDispatcher("/").forward(arg0, arg1);
		session = null;

	}

}
